import React, { Component } from 'react'
import { Layout, Modal, notification } from 'antd'
import { AudioOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
const { Sider } = Layout
import { ipcRenderer, shell } from 'electron'
import { bindAll } from 'underscore'
import { write, writenull } from '../utils/ports'
import { delay } from '../utils/time'
import { ipctype } from '../main/interface'
import Index1 from './d/index'
import Audio1 from './d/audio'
import Video1 from './d/video'
import { facetype, Showindex } from './types'
import { version } from '../../package.json'
import { publish } from '../../electron-builder.json'
import Setup from './d/setup'


const other = ['Prayer', 'Heart_1', 'Heart_2', 'Heart_3', 'Honour', 'Congratulation', 'Other', 'Face']
const isDevelopment = process.env.NODE_ENV !== "production";


window.onload = function () {
  if (!isDevelopment) {
    const href = `${publish.url}package.json`
    const v = ipcRenderer.sendSync('up', href)
    if (v && version != v) {
      Modal.confirm({
        title: '有新的更新是否查看',
        icon: <ExclamationCircleOutlined />,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          shell.openExternal(publish.url)
        }
      });
    }
  }
}


function error() {
  Modal.error({
    content: '无法开启摄像头',
    cancelText: '重试',
  })
}

type State = {
  showindex: Showindex,
  display: 'block' | 'none',
  text: string,
  bashou: string,
  start: boolean,
  wifi: number,
  icon?: string,
  facetype: facetype,
}

const icon = ['#iconduihao', '#icondengdai']


export type Zwifi = {
  color: string,
  percent: number
}

type Props = {}

export default class Demo extends Component<Props, State> {
  timer: any
  constructor(prop: Props) {
    super(prop)
    bindAll(this, 'setdis', 'setshowindex', 'setstart', 'seticon', 'setfacetype')
    this.timer = 1
    this.state = {
      showindex: 'index',
      display: 'none',
      text: '',
      bashou: 'bashou',
      start: true,
      wifi: 10,
      icon: undefined,
      facetype: 'head',
    }

    ipcRenderer.send('portweb', true)
    window.onbeforeunload = function () {
      ipcRenderer.send('portweb', false)
    }

    ipcRenderer.on(ipctype['change-head'], async (_event, _arg, str, name, t: string, timer: number) => {
      if (str) {
        write(str)
      } else {
        writenull(t)
      }
      // 设置最小值750
      if (timer < 750) {
        await delay(750 - timer)
      }
      this.setState({
        text: t,
        start: true,
        wifi: timer || 0,
        icon: icon[0]
      })
      if (name) {
        const img = document.querySelector<HTMLImageElement>('#img')
        if (!img) return
        if (other.includes(name)) {
          const ca = document.getElementById('canvas') as HTMLCanvasElement
          var data = ca.toDataURL('image/png')
          img.src = data
        } else {
          img.src = ''
          img.className = "img-" + name
        }
      }
    })
  }

  setshowindex(showindex: Showindex) {
    this.setState({
      showindex,
    })
    if (showindex == 'video') {
      this.setState({
        start: true
      })
    } else {
      this.setState({
        start: false
      })
    }
  }
  setstart(start: boolean) {
    this.setState({
      start
    })
  }
  seticon(icon: string) {
    this.setState({
      icon
    })
  }

  setdis(display: State['display']) {
    let bashou = 'bashou'
    if (display == 'block') {
      bashou = 'bashou bashouactive'
    }
    this.setState({
      display,
      bashou
    })
  }


  mediaevent() {
    location.replace('index.html?a=1#/resources')
  }

  componentDidMount() {
    this.timer = setInterval(() => {
      if (this.state.icon === icon[0]) {
        this.setState({
          icon: ''
        })
      }
    }, 1000)
    setTimeout(() => {
      if (navigator.onLine) return
      notification.open({
        message: '没有网络',
        description: '请检查是否WiFi连接正常',
      });

    }, 2000)
  }

  componentWillUnmount() {
    clearInterval(this.timer)
  }

  componentDidUpdate(_: any, prstate: State) {
    if (prstate.showindex !== this.state.showindex) {
      if (this.state.showindex == 'index') {
        this.setdis('none')
      }
    }
  }

  fullscreen() {
    ipcRenderer.send('fullscreen', false)

  }
  replace() {
    location.reload()
  }

  setfacetype(data: facetype) {
    this.setState({
      facetype: data
    })
  }

  render() {
    const { showindex, display, text, bashou, start, wifi, facetype } = this.state
    return <Layout id="demo">
      <Layout>
        {
          showindex == 'index' ? <Index1 fullscreen={this.fullscreen} setshowindex={this.setshowindex}></Index1> : <></>
        }
        {
          showindex == 'video' ? <Video1 replace={this.replace} wifi={wifi} setfacetype={this.setfacetype} fullscreen={this.fullscreen} type={facetype} icon={this.state.icon} seticon={this.seticon} error={error} display={display} setdis={this.setdis} bashou={bashou} start={start} setstart={this.setstart} ></Video1> : <></>
        }
        {
          showindex == 'audio' ? <Audio1 fullscreen={this.fullscreen} replace={this.replace} wifi={wifi} icon={this.state.icon} seticon={this.seticon} text={text} display={display} setdis={this.setdis} bashou={bashou}></Audio1> : <></>
        }
        {
          showindex == 'setup' ? <Setup fullscreen={this.fullscreen} setIndex={this.setshowindex} ></Setup> : <></>
        }
      </Layout>
      {
        showindex !== 'index' ? <div className={bashou} onClick={() => { display == 'none' ? this.setdis('block') : this.setdis('none') }} ></div> : <></>
      }
      <Sider className="right" width="150" style={{ display: display }}  >
        <ul>
          <li className={showindex == "video" ? "active" : ''}>
            <svg className="icon" aria-hidden="true" onClick={() => this.setshowindex('video')}>
              <use xlinkHref="#iconluxiang"></use>
            </svg>
          </li>
          <li className={showindex == "audio" ? "active" : ''}>
            <AudioOutlined className="icon" aria-hidden="true" onClick={() => this.setshowindex('audio')} />
          </li>
          <li>
            <svg className="icon" onClick={() => { this.mediaevent() }} aria-hidden="true" >
              <use xlinkHref="#icondaima"></use>
            </svg>
          </li>
        </ul>
      </Sider>
    </Layout >
  }
}

